package com.doge.calcalbum.business.note

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.doge.calcalbum.core.base.LoadStatus
import com.doge.calcalbum.db.model.Note
import com.doge.calcalbum.utils.db
import com.doge.calcalbum.utils.runOnIO
import java.io.File

class NoteViewModel constructor(
    private val repository: NoteRepository
) : ViewModel() {
    val noteList: LiveData<List<Note>> = repository.noteList
    val loading: LiveData<LoadStatus> = repository.loading
    val noteContent = MutableLiveData<String>()

    fun edit(noteId: Int?, title: String, content: String) {
        if (noteId == null) {
            repository.insert(title, content)
        } else {
            repository.update(noteId, title, content)
        }
    }

    fun delete(data: List<Note>) {
        repository.delete(data)
    }

    fun query(noteId: Int) = runOnIO {
        val note = db.noteDao().queryById(noteId) ?: return@runOnIO
        val content = NoteUtils.read(File(note.filePath))
        noteContent.postValue(content)
    }
}

class NoteViewModelFactory : ViewModelProvider.Factory {
    override fun <T : ViewModel?> create(modelClass: Class<T>): T {
        val repository = NoteRepository()
        if (modelClass.isAssignableFrom(NoteViewModel::class.java)) {
            return NoteViewModel(repository) as T
        }
        //noinspection unchecked
        throw IllegalArgumentException("Unknown ViewModel class")
    }
}


